﻿using System;
using System.ComponentModel;
using System.ServiceProcess;
using System.Threading;

namespace WatcherService
{
    public partial class WatchMoves : ServiceBase
    {
        public WatchMoves()
        {
            InitializeComponent();
        }

        private static BackgroundWorker wrk = null;

        protected override void OnStart(string[] args)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(DoWork);
            worker.WorkerReportsProgress = false;
            worker.WorkerSupportsCancellation = true;
            worker.RunWorkerCompleted +=
               new RunWorkerCompletedEventHandler(WorkerCompleted);

            wrk = worker;

            worker.RunWorkerAsync(); //we can also pass parameters to the async method....
        }
        private static void DoWork(object sender, DoWorkEventArgs e)
        {
            while (DateTime.Now.Second != 0 || DateTime.Now.Minute % 1 != 0)
            {
                Thread.Sleep(500);
            }
            GameHandler.PerformHandle();
        }

        private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            if (worker != null)
            {
                // sleep for 20 secs and again call DoWork to get FxRates..we can increase the time to sleep and make it configurable to the needs
                System.Threading.Thread.Sleep(5000);
                worker.RunWorkerAsync();
            }
        }
        protected override void OnStop()
        {
            //If background worker process is running then clean up that object.
            if (wrk != null)
            {
                wrk.CancelAsync();
            }
        }
    }
}
